import { View, Text, Image, ScrollView } from '@tarojs/components'
import Taro, { useLoad } from '@tarojs/taro'
import { useState } from 'react'
import { MoreOutlined  } from '@taroify/icons'

export default function Index() {
  const [users, setUsers] = useState<any[]>([])

  useLoad(() => {
    fetchUsers()
  })

  const fetchUsers = async () => {
    try {
      const app = Taro.getApp()
      // @ts-ignore
      const API_BASE = app?.globalData?.apiBase || Taro.getStorageSync('API_BASE') || 'http://localhost:3000'
      // @ts-ignore
      const currentUserId = app?.globalData?.currentUserId
      const res = await Taro.request({ url: `${API_BASE}/users`, method: 'GET', data: { currentUserId } })
      if ((res.statusCode as number) >= 200 && (res.statusCode as number) < 300) {
        setUsers(res.data as any[])
      }
    } catch (e) {
      Taro.showToast({ title: '获取用户失败', icon: 'none' })
    }
  }

  return (
    <ScrollView scrollY style={{ height: '100vh' }}>
      <View style={{ padding: '12px 16px', fontWeight: 'bold' }}>首页</View>
      <View
        style={{ padding: '8px 16px', display: 'flex', justifyContent: 'flex-end' }}
        onClick={() => Taro.navigateTo({ url: '/pages/message/message' })}
      >
        <MoreOutlined size={28} />
      </View>
      {users.map((u) => (
        <View
          key={u._id}
          style={{ display: 'flex', alignItems: 'center', padding: '12px 16px', borderBottom: '1px solid #eee' }}
          onClick={async () => {
            try {
              const app = Taro.getApp()
              // @ts-ignore
              const API_BASE = app?.globalData?.apiBase || Taro.getStorageSync('API_BASE') || 'http://localhost:3000'
              // @ts-ignore
              const currentUserId = app?.globalData?.currentUserId
              const open = await Taro.request({ url: `${API_BASE}/chats/open`, method: 'POST', data: { a: currentUserId, b: u._id } })
              const chatId = open?.data?._id
              if (chatId) {
                Taro.navigateTo({ url: `/pages/chat/chat?chatId=${chatId}&peerId=${u._id}` })
              }
            } catch (e) {
              Taro.showToast({ title: '开启会话失败', icon: 'none' })
            }
          }}
        >
          <Image src={u.avatar} style={{ width: '40px', height: '40px', borderRadius: '50%', marginRight: '10px' }} />
          <Text>{u.username}</Text>
        </View>
      ))}
      {users.length === 0 && (
        <View style={{ padding: '24px', color: '#888' }}>暂无其他用户</View>
      )}
    </ScrollView>
  )
}

